// pages/register/register.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {
      username: "",
      password: ""
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  formSubmit(e) {
    console.log(e.detail.value)
    var data = e.detail.value
    var user = {
      username: "",
      password: ""
    }
    this.ifUserNameRepeat(data,user)
  },

  createUser(data,user) {
    if (data.passWord == data.passWord2) {
      user.username = data.userName
      user.password = data.passWord
      console.log(user)
      wx.request({
        url: 'http://daxian.viphk.ngrok.org/user/addUser',
        data: user,
        success(res) {
          console.log(res)
          wx.showToast({
            title: '创建成功'
          })
          wx.navigateBack({
            delta: 1,
          })
        }
      })
    } else {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'error'
      })
    }
  },

  ifUserNameRepeat(data,user) {
    var that = this
    wx.request({
      url: 'http://daxian.viphk.ngrok.org/user/queryUserByUserName', //仅为示例，并非真实的接口地址
      data: {
        username: data.userName
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data === "") {
          that.createUser(data,user)
        } else {
          wx.showToast({
            title: '账户已存在',
            icon:'error'
          })
        }
      }
    })
  }
})